/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package serversidepkg;

import backendpkg.DataSource;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author smag
 */
public class GetMessage extends HttpServlet {
   
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    	response.setContentType("text/xml");
    	   
        try {
        	response.setHeader("Cache-Control","no-cache"); //Forces caches to obtain a new copy of the page from the origin server
        	response.setHeader("Cache-Control","no-store"); //Directs caches not to store the page under any circumstance
        	response.setDateHeader("Expires", 0); //Causes the proxy cache to see the page as "stale"
        	response.setHeader("Pragma","no-cache"); //HTTP 1.0 backward compatibility
        	
        	//Get connection to database
            DataSource datasource = new DataSource();
            Connection conn = datasource.getConnection();
            PreparedStatement statement;
            
        	//Get username from session
			HttpSession session = request.getSession();			
            String user = (String) session.getAttribute("username");

            if (user == null) {
               request.setAttribute("Error", "Session has ended.  Please login.");
               RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
               rd.forward(request, response);
            }else{       	
	            String chat = request.getParameter("chat");
	            String last = request.getParameter("last");
	
	            response.setHeader("Cache Control", "no-cache");
	
	            if(!last.equals(""))
	            {
	                String sql = "SELECT message_id, user, message_text, date_format(time, '%h:%i') as time" +
	                			" FROM Message WHERE chat_id = ? AND message_id > ?";
	
	                statement = (PreparedStatement) conn.prepareStatement(sql);
	                statement.setInt(1, Integer.parseInt(chat));
	                statement.setInt(2, Integer.parseInt(last));
	                ResultSet result = statement.executeQuery();
	
	                //Prepare xml string used to memorize messages
	                String xml="";
	                
	                xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?><root>";
	
	                while(result.next()){
	                    xml+="<message id=\""+ result.getInt("message_id")+ "\">";
	                    xml+="<user>"+ result.getString("user")+ "</user>";
	                    xml+="<text>"+ result.getString("message_text")+ "</text>";
	                    xml+="<time>"+ result.getString("time")+ "</time>";
	                    xml+="</message>";
	                }
	                
	                xml+="</root>";
	                 
	                conn.close();
	                
	                response.getWriter().write(xml);
	            }
            }
        } catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
    } 

}
